package com.solr;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by thinkjoy on 2017/6/30.
 */
public class SolrTest {

    /**
     * 添加/修改索引
     * @throws Exception
     */
    public static void addIndex() throws Exception{
        HttpSolrClient server=SolrServer.getServer();
        Collection<SolrInputDocument> documents=new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            SolrInputDocument document=new SolrInputDocument();
            document.addField("id",1003+i);
            document.addField("name_s","test"+i);//_s表示string类型
            document.addField("score_i",103+i);//_i表示整型
            documents.add(document);
        }
        server.add(documents);
        server.commit();
    }

    /**
     * 根据id删除索引
     * @param id
     * @throws Exception
     */
    public static void deleteById(String id) throws Exception{
        HttpSolrClient server=SolrServer.getServer();
        server.deleteById(id);
        server.commit();
    }

    /**
     * list批量删除
     * @param ids
     */
    public static void deleteByList(List<String> ids) throws Exception{
        HttpSolrClient server=SolrServer.getServer();
        server.deleteById(ids);
        server.commit();
    }

    /**
     * 查询索引
     * @throws Exception
     */
    public static void query() throws Exception{
        HttpSolrClient server=SolrServer.getServer();
        SolrQuery query=new SolrQuery();
        query.setQuery("*:*");
        query.setStart(0);//开始查询的记录数
        query.setRows(10000);//总条数
        QueryResponse response=server.query(query);
        SolrDocumentList results=response.getResults();
        System.out.println("总条数:"+results.getNumFound());
        for (int i = 0; i <results.size() ; i++) {
            System.out.println(results.get(i).getFieldNames());
            System.out.println(results.get(i).getFieldValue("name_s"));
        }
    }

    public static void main(String[] args) throws Exception{
        addIndex();
        deleteById("1003");
        query();
    }
}
